#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
彻底修复MES系统中的所有语法错误
"""

import os
import re

def fix_warehouse_models():
    """专门修复warehouse/models.py文件"""
    
    file_path = 'apps/warehouse/models.py'
    
    if not os.path.exists(file_path):
        print(f"文件不存在: {file_path}")
        return
    
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        original_content = content
        
        # 具体的修复模式
        replacements = [
            # 修复第393行的问题
            (r'ForeignKey\(TransportList, on_delete=models\.CASCADE related_name = "transport_list_details", verbose_name=_\("transport_list"\)\)',
             'ForeignKey(TransportList, on_delete=models.CASCADE, related_name="transport_list_details", verbose_name=_("transport_list"))'),
            
            # 修复第396行的问题
            (r'ForeignKey\(Item, on_delete=models\.CASCADE related_name = "transport_list_detail", verbose_name=_\("item"\)\)',
             'ForeignKey(Item, on_delete=models.CASCADE, related_name="transport_list_detail", verbose_name=_("item"))'),
            
            # 修复第401行的问题
            (r'ForeignKey\(User, on_delete=models\.CASCADE verbose_name=_\("updated_by"\)\)',
             'ForeignKey(User, on_delete=models.CASCADE, verbose_name=_("updated_by"))'),
            
            # 修复第403行的问题
            (r'ForeignKey\(ContentType, on_delete=models\.CASCADE blank=True, null=True\)',
             'ForeignKey(ContentType, on_delete=models.CASCADE, blank=True, null=True)'),
            
            # 修复第407行的问题
            (r'ForeignKey\(Location, on_delete=models\.CASCADE related_name="transport_list_details", verbose_name=_\("location"\)\)',
             'ForeignKey(Location, on_delete=models.CASCADE, related_name="transport_list_details", verbose_name=_("location"))'),
            
            # 修复第452行的问题
            (r'ForeignKey\(\'manufactureplan\.ManufacturePlan\', on_delete=models\.CASCADE related_name=\'applications\', verbose_name=_\("manufactureplan"\)\)',
             'ForeignKey("manufactureplan.ManufacturePlan", on_delete=models.CASCADE, related_name="applications", verbose_name=_("manufactureplan"))'),
            
            # 修复第453行的问题
            (r'ForeignKey\(\'technologies\.Technology\', on_delete=models\.CASCADE related_name="applications", verbose_name=_\("technology"\)\)',
             'ForeignKey("technologies.Technology", on_delete=models.CASCADE, related_name="applications", verbose_name=_("technology"))'),
            
            # 修复第468行的问题
            (r'ForeignKey\(ItemJournal, on_delete=models\.CASCADE related_name=\'entries\', verbose_name=_\(\'journal\'\)\)',
             'ForeignKey(ItemJournal, on_delete=models.CASCADE, related_name="entries", verbose_name=_("journal"))'),
            
            # 修复第471行的问题
            (r'ForeignKey\(Item, on_delete=models\.CASCADE related_name=\'item_entries\', verbose_name =_\(\'item\'\)\)',
             'ForeignKey(Item, on_delete=models.CASCADE, related_name="item_entries", verbose_name=_("item"))'),
            
            # 修复第472行的问题
            (r'ForeignKey\(Location, on_delete=models\.CASCADE related_name=\'item_entries\', verbose_name =_\(\'location\'\)\)',
             'ForeignKey(Location, on_delete=models.CASCADE, related_name="item_entries", verbose_name=_("location"))'),
            
            # 修复第476行的问题
            (r'ForeignKey\(User, on_delete=models\.CASCADE verbose_name =_\(\'updated_by\'\)\)',
             'ForeignKey(User, on_delete=models.CASCADE, verbose_name=_("updated_by"))'),
            
            # 修复第479行的问题
            (r'ForeignKey\(\'customer\.Customer\', on_delete=models\.CASCADE related_name=\'item_entries\', blank=True, null=True, verbose_name=_\("material owner"\)\)',
             'ForeignKey("customer.Customer", on_delete=models.CASCADE, related_name="item_entries", blank=True, null=True, verbose_name=_("material owner"))'),
            
            # 修复第482行的问题
            (r'ForeignKey\(TransportListDetail, on_delete=models\.CASCADE related_name=\'item_entry\', blank=True, null=True, verbose_name=_\("transport_list_detail"\)\)',
             'ForeignKey(TransportListDetail, on_delete=models.CASCADE, related_name="item_entry", blank=True, null=True, verbose_name=_("transport_list_detail"))'),
            
            # 修复第522行的问题
            (r'ForeignKey\(Item, on_delete=models\.CASCADE related_name=\'prices\', verbose_name=_\(\'item\'\)\)',
             'ForeignKey(Item, on_delete=models.CASCADE, related_name="prices", verbose_name=_("item"))'),
            
            # 修复第563行的问题
            (r'ForeignKey\(Expense, on_delete=models\.CASCADE verbose_name=_\(\'expense\'\)\)',
             'ForeignKey(Expense, on_delete=models.CASCADE, verbose_name=_("expense"))'),
            
            # 修复第581行的问题
            (r'ForeignKey\(User, on_delete=models\.CASCADE related_name=\'transfer_list\', verbose_name=_\("applicat transfer_list"\)\)',
             'ForeignKey(User, on_delete=models.CASCADE, related_name="transfer_list", verbose_name=_("applicat transfer_list"))'),
            
            # 修复第611行的问题
            (r'ForeignKey\(ItemEntry, on_delete=models\.CASCADE related_name=\'entry_logs\', verbose_name=_\("item entry"\)\)',
             'ForeignKey(ItemEntry, on_delete=models.CASCADE, related_name="entry_logs", verbose_name=_("item entry"))'),
            
            # 修复第632行的问题
            (r'ForeignKey\(TransportListDetail, on_delete=models\.CASCADE unique=True, verbose_name=_\(\'transport list detail\'\)\)',
             'ForeignKey(TransportListDetail, on_delete=models.CASCADE, unique=True, verbose_name=_("transport list detail"))'),
            
            # 修复第636行的问题
            (r'ForeignKey\(ItemEntry, on_delete=models\.CASCADE related_name=\'transport_detail_from\', blank=True, null=True, verbose_name=_\(\'from item entry\'\)\)',
             'ForeignKey(ItemEntry, on_delete=models.CASCADE, related_name="transport_detail_from", blank=True, null=True, verbose_name=_("from item entry"))'),
            
            # 修复第637行的问题
            (r'ForeignKey\(ItemEntry, on_delete=models\.CASCADE related_name=\'transport_detail_to\', blank=True, null=True, verbose_name=_\(\'to item entry\'\)\)',
             'ForeignKey(ItemEntry, on_delete=models.CASCADE, related_name="transport_detail_to", blank=True, null=True, verbose_name=_("to item entry"))'),
            
            # 修复第641行的问题
            (r'ForeignKey\(ItemEntry, on_delete=models\.CASCADE related_name=\'transport_detail_inventory\', blank=True, null=True, verbose_name=_\(\'inventory item entry\'\)\)',
             'ForeignKey(ItemEntry, on_delete=models.CASCADE, related_name="transport_detail_inventory", blank=True, null=True, verbose_name=_("inventory item entry"))'),
        ]
        
        # 应用所有替换
        for pattern, replacement in replacements:
            content = re.sub(pattern, replacement, content)
        
        # 通用的逗号修复
        generic_patterns = [
            # 修复 on_delete 后缺少逗号的问题
            (r'(on_delete=models\.CASCADE)\s+(related_name=)', r'\1, \2'),
            (r'(on_delete=models\.CASCADE)\s+(verbose_name=)', r'\1, \2'),
            (r'(on_delete=models\.CASCADE)\s+(blank=True)', r'\1, \2'),
            (r'(on_delete=models\.CASCADE)\s+(null=True)', r'\1, \2'),
            (r'(on_delete=models\.CASCADE)\s+(unique=True)', r'\1, \2'),
            
            # 修复其他字段属性之间缺少逗号的问题
            (r'(related_name="[^"]*")\s+(verbose_name=)', r'\1, \2'),
            (r'(related_name="[^"]*")\s+(blank=True)', r'\1, \2'),
            (r'(related_name="[^"]*")\s+(null=True)', r'\1, \2'),
            (r'(blank=True)\s+(null=True)', r'\1, \2'),
            (r'(null=True)\s+(verbose_name=)', r'\1, \2'),
            (r'(null=True)\s+(related_name=)', r'\1, \2'),
            (r'(unique=True)\s+(verbose_name=)', r'\1, \2'),
        ]
        
        for pattern, replacement in generic_patterns:
            content = re.sub(pattern, replacement, content)
        
        # 如果内容有变化，写回文件
        if content != original_content:
            with open(file_path, 'w', encoding='utf-8') as f:
                f.write(content)
            print(f"修复了 {file_path}")
        else:
            print(f"{file_path} 无需修复")
            
    except Exception as e:
        print(f"修复 {file_path} 时出错: {e}")

def fix_all_models():
    """修复所有模型文件"""
    
    # 通用的逗号修复模式
    generic_patterns = [
        (r'(on_delete=models\.CASCADE)\s+(related_name=)', r'\1, \2'),
        (r'(on_delete=models\.CASCADE)\s+(verbose_name=)', r'\1, \2'),
        (r'(on_delete=models\.CASCADE)\s+(blank=True)', r'\1, \2'),
        (r'(on_delete=models\.CASCADE)\s+(null=True)', r'\1, \2'),
        (r'(on_delete=models\.CASCADE)\s+(unique=True)', r'\1, \2'),
        (r'(related_name="[^"]*")\s+(verbose_name=)', r'\1, \2'),
        (r'(related_name="[^"]*")\s+(blank=True)', r'\1, \2'),
        (r'(related_name="[^"]*")\s+(null=True)', r'\1, \2'),
        (r'(blank=True)\s+(null=True)', r'\1, \2'),
        (r'(null=True)\s+(verbose_name=)', r'\1, \2'),
        (r'(null=True)\s+(related_name=)', r'\1, \2'),
        (r'(unique=True)\s+(verbose_name=)', r'\1, \2'),
    ]
    
    # 遍历所有Python文件
    for root, dirs, files in os.walk('apps'):
        for file in files:
            if file.endswith('.py') and file != '__init__.py':
                file_path = os.path.join(root, file)
                
                try:
                    with open(file_path, 'r', encoding='utf-8') as f:
                        content = f.read()
                    
                    original_content = content
                    
                    # 应用所有修复模式
                    for pattern, replacement in generic_patterns:
                        content = re.sub(pattern, replacement, content)
                    
                    # 如果内容有变化，写回文件
                    if content != original_content:
                        with open(file_path, 'w', encoding='utf-8') as f:
                            f.write(content)
                        print(f"修复了 {file_path}")
                        
                except Exception as e:
                    print(f"处理 {file_path} 时出错: {e}")

if __name__ == '__main__':
    print("=== 彻底修复MES系统语法错误 ===")
    
    # 首先修复warehouse模型
    print("\n1. 修复warehouse模型...")
    fix_warehouse_models()
    
    # 然后修复其他所有模型
    print("\n2. 修复其他模型...")
    fix_all_models()
    
    print("\n=== 修复完成 ===") 